<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.beaut.project.util.FlowUtility" %>
<%@ page import="com.beaut.project.util.StaticData" %>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "0" : request.getParameter("isShow");
	String type = request.getParameter("type") == null ? "" : request.getParameter("type");
	String gd_id = request.getParameter("gd_id") == null ? "" : request.getParameter("gd_id");
	String dept_id = request.getParameter("dept_id") == null ? "" : request.getParameter("dept_id");
	String dept_name = request.getParameter("dept_name") == null ? "" : request.getParameter("dept_name");
	String gd_code = request.getParameter("gd_code") == null ? "" : request.getParameter("gd_code");
	String gd_name = request.getParameter("gd_name") == null ? "" : request.getParameter("gd_name");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建还款单":"编辑还款单" %></title>
			<link href="<%=contextPath%>/public/css/smart_wizard_vertical.css" rel="stylesheet"	type="text/css">
		<script type="text/javascript" src="<%=contextPath%>/public/js/jquery.smartWizard.js"></script>
		<link  rel="stylesheet"  href  ="<%=contextPath%>/public/swfupload/css/swfupload.css">
	
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
			.tdg{
			padding-top:10px;
			padding-bottom:5px;
			font-size: 12px;
			background-color: #c0ebd7;
			width:20%;
		}
		.tdb{
			padding:5px;
			width:30%;
		}
		</style>
		  <script  type="text/javascript"  src="<%=contextPath%>/core/js/datastructs.js"  ></script>
			<script  type="text/javascript"  src="<%=contextPath%>/core/js/sys.js"  ></script>
			<script  type="text/javascript"  src="<%=contextPath%>/core/js/prototype.js"  ></script>
		<script type="text/javascript" src="<%=contextPath%>/public/swfupload/js/attachMenu.js"></script>
		<script type="text/javascript" src="<%=contextPath%>/public/swfupload/js/Menu.js"></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/swfupload.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/fileprogress.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/handlers.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/swfupload.queue.js"  ></script>
	<script type="text/javascript">
	var flag="<%=flag%>";
	var isShow="<%=isShow%>";
	var lastIndex;
	jQuery(document).ready(function() {
		if(flag == '1'){
			jQuery('#lp').form({
				onLoadSuccess:function(){
					queueCompleteOver();
				}
			});
		}else{
			jQuery("#operation_date").datetimebox('setValue',getTodaySecond());
			var param="gd_id=<%=gd_id%>";
			jQuery.ajax({
					type:'GET',
					url:'<%=contextPath %>/springMVC/gd/getGDContentByGDId',
					dataType:"JSON",
					data:param,
					success:function(rtJson){
						jQuery("#fb_advances_id").val(rtJson.gd_worker_id);
						jQuery("#fb_advances").val(rtJson.gd_worker_name);
					}
				});
		}
		<%=isAdd?"":"jQuery('#lp').form('load','"+contextPath+"/springMVC/gd/getGdYetAdvancesById?id="+id+"');"%>
		
		jQuery("#table").datagrid({
			title:"分包商垫款",
			iconCls:'icon-zc',
			loadMsg:'正在加载数据，请稍后......',
			<%=isAdd?"url:'',":"url:'"+contextPath+"/springMVC/gd/listPageGdYetAdvancesDetail?voucher_id="+id+"',"%>
			rownumbers:true,
			fitColumns:true,
			singleSelect:true,
			idField:'id',
			frozenColumns:[[
			      {field:'ck',checkbox:true},
			      {title:'主键',field:'id',hidden:true},
			      {title:'还款单id',field:'yet_id',hidden:true},
			      {title:'借款单id',field:'advances_id',hidden:true}
			]],
			columns:[[
				{title:'分包商',field:'fb_advances',width:100,align:'center'},
				{title:'放款日期',field:'actual_operation_date',width:100,align:'center',sort:true},
				{title:'经办人',field:'person_name',width:100,align:'center'},
				{title:'垫款金额',field:'money',width:100,align:'center'},
				{title:'结余本金',field:'on_money',width:100,align:'center'},
				{title:'利率',field:'rate',width:100,align:'center'},
				{title:'利息',field:'lxMoney',width:100,align:'center',formatter:function(value,rowData,rowIndex){
					return rowData.lxMoney=jsRate(rowData);
				}},
				{title:'已还金额',field:'already_money',width:100,align:'center'},
				{title:'本次还款金额',field:'yet_money',width:100,align:'center',editor:{
					type:'numberbox',
					options:{
						min:0,
						precision:2
					}
				}}
			
			]],
			pageSize:10,
			pageList : [10,50,100],  
			pagination:true,
			onBeforeLoad:function(){
				jQuery(this).datagrid('rejectChanges');
			},
			onAfterEdit:function(rowIndex, rowData, changes){
				jsRate(rowData);
				sumMoney();
				},
			onClickCell:function(rowIndex,field,value){
				if (lastIndex != rowIndex){
					jQuery('#table').datagrid('endEdit', lastIndex);
					jQuery('#table').datagrid('beginEdit', rowIndex);
					var ed = jQuery('#table').datagrid('getEditor', {index:rowIndex,field:field});
					if(ed == null){
						ed = jQuery('#table').datagrid('getEditor', {index:rowIndex,field:'yet_money'});
					}
					jQuery(ed.target).select();
				}
				lastIndex = rowIndex;
			},
			toolbar:[
				{
					id:'add',
					text:'选择垫款单',
					disabled:false,
					iconCls:'icon-add',
					handler:function(){
						  var fb_advances_id = jQuery('#fb_advances_id').val();
						  if(fb_advances_id==""){
							  jQuery.messager.alert('提示：','请先选择分包商!!');
							  return false;
						  }
						openDialogResize('<%=contextPath %>/springViews/gd/choseAdvances.jsp?callback=rtCallBack&gd_id=<%=gd_id%>&dept_id=<%=dept_id%>&dept_name=<%=dept_name%>&gd_code=<%=gd_code%>&gd_name=<%=gd_name%>&fb_advances_id='+fb_advances_id,1000, 800);
					}
				},'-',{
				id:'save',
				text:'保存修改',
				disabled:false,
				iconCls:'icon-save',
				handler:function(){
					jQuery('#table').datagrid('acceptChanges');
					var data = jQuery('#table').datagrid('getData');
					jQuery('#table').datagrid('loadData',data);
					sumMoney();
					lastIndex =-1;
				}
				},'-',{
				id:'delete',
				text:'删除',
				disabled:false,
				iconCls:'icon-remove',
				handler:function(){
					jQuery('#table').datagrid('acceptChanges');
					lastIndex =-1;
					var rows = jQuery('#table').datagrid('getSelections');
					if (rows.length > 0){
						for(var i=0;i<rows.length;i++){
							var row = rows[i];
							var index = jQuery('#table').datagrid('getRowIndex', row);
							jQuery('#table').datagrid('deleteRow', index);
							var sumMoneys=jQuery("#sum_money").numberbox("getValue");
							var money=0;
							if(parseFloat(sumMoneys)-parseFloat(row.yet_money)>0){
						    jQuery("#sum_money").numberbox("setValue",parseFloat(sumMoneys)- parseFloat(row.yet_money));
							}else{
						    jQuery("#sum_money").numberbox("setValue",money);
							}
						}
					}
					var data = jQuery('#table').datagrid('getData');
					jQuery('#table').datagrid('loadData',data);
				}
			}
		   ],
			onLoadSuccess:function(rtJson){
				if(rtJson.rtState== '1')
				{
					jQuery.messager.alert('提示',rtJson.rtMsrg);
				}
			}
		});
		
		 var settings = {
			      flash_url : "<%=contextPath%>/public/swfupload/swfupload.swf",
			      upload_url: "<%=contextPath%>/springMVC/fileUpload/fileupload",
			      post_params: {
			    	 "module" : "<%=com.beaut.project.util.StaticData.GD_MODULE%>"
			      },
			      file_size_limit : "100 MB",
			      file_types : "*.*",
			      file_types_description : "All Files",
			      file_upload_limit : 100,
			      file_queue_limit : 0,
			      custom_settings : {
			        uploadArea : "fsUploadArea",
			        progressTarget : "fsUploadProgress",
			        startButtonId : "btnStart",
			        cancelButtonId : "btnCancel"
			      },
			      debug: false,
			      button_image_url: "<%=contextPath%>/public/swfupload/img/uploadx4.gif",
			      button_width: "65",
			      button_height: "29",
			      button_placeholder_id: "spanButtonUpload",
			      button_text: '<span class=\"textUpload\">上传附件</span>',
			      button_text_style: ".textUpload{color:#0000ff;}",
			      button_text_top_padding : 1,
			      button_text_left_padding : 18,
			      button_width: 80,
			      button_height: 20,
			      button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			      button_cursor: SWFUpload.CURSOR.HAND,
			      
			      file_queued_handler : fileQueued,
			      file_queue_error_handler : fileQueueError,
			      file_dialog_complete_handler : fileDialogComplete,
			      upload_start_handler : uploadStart,
			      upload_progress_handler : uploadProgress,
			      upload_error_handler : uploadError,
			      upload_success_handler : uploadSuccessOver,
			      upload_complete_handler : uploadComplete,
			      queue_complete_handler : queueCompleteOver
			    };
			    swfupload = new SWFUpload(settings);
			  
			});
		
	 function uploadSuccessOver(file, serverData){
			  try {
			    var progress = new FileProgress(file, this.customSettings.progressTarget);
			    progress.toggleCancel(false);
			    var json = null;
			    json = serverData.evalJSON();
			    if(json.rtState=="1") {
			       progress.setError();
			       progress.setStatus("上传失败");
			    } else {
			       if($('attachmentId').value!=null && $('attachmentId').value!=""){
			    	 $('attachmentId').value += ',' + json.rtData.attachmentId;
			       } 
			       else{
			    	   $('attachmentId').value = json.rtData.attachmentId;
			       }
			       if($('attachmentName').value!=null && $('attachmentName').value!=""){
			    	 $('attachmentName').value += '*' + json.rtData.attachmentName;
			       } 
			       else{
			    	   $('attachmentName').value = json.rtData.attachmentName;
			       }
			    }
			  } catch (ex) {
			    this.debug(ex);
			  }
	}
	function queueCompleteOver(){
		var attachmentIds = $("attachmentId").value;
	    var attachmentNames = $("attachmentName").value;
	    if(attachmentIds){
	      jQuery('#attaTr').show();
      	  jQuery('#fsUploadArea').hide();
      	  if('<%=isShow%>' == 1){
	       	  	attachMenuUtil("showAtt",null,null,attachmentNames,attachmentIds,true,'attach');
	     }else{
	       	  	attachMenuUtil("showAtt",null,null,attachmentNames,attachmentIds,false,'attach');
	     }
	    }
	 }
			 
	  function deleteAttachment(attachmentId,attachmentName){
		  var attrIds = $("attachmentId").value;
	    var attrNames = $("attachmentName").value;
	     var attrIdArrays = attrIds.split(",");
		  var attrNameArrays = attrNames.split("*");
		 var idArray = new Array();
		 var nameArray = new Array();
		 
		 for(var i=0;i<attrIdArrays.length;i++){
			 if(attrIdArrays[i] != attachmentId){
				 idArray.push(attrIdArrays[i]);
				 nameArray.push(attrNameArrays[i]);
			 }
		 }
		 $("attachmentId").value = idArray.join(",");
		 $("attachmentName").value = nameArray.join("*");
		 if($("attachmentId").value == ""){
			 jQuery('#attaTr').hide();
		 }
	  }
	  
	  
		function doSubmit(obj){
			//自动提交数据
			jQuery('#table').datagrid('acceptChanges');
			lastIndex =-1;
			var sum_money=0;
			if(jQuery('#ff').form('validate')){
				var products="";
				var jsondata=jQuery("#table").datagrid("getData");
				for(var i=0;i<jsondata.total;i++){
					if(products!=""){
						products+=";";
					}
					products+=jsonToStr(jsondata.rows[i]);
					sum_money+=parseFloat(jsondata.rows[i].yet_money);
					if(parseFloat(jsondata.rows[i].yet_money)>parseFloat(parseFloat(jsondata.rows[i].on_money)+parseFloat(jsondata.rows[i].lxMoney))){
						jQuery.messager.alert("提示","【第"+[i+1]+"行】班组还垫款金额不能大于欠款金额(本金+利息)！");
						return;
					}
				}
			}
			if(parseFloat(sum_money)<=0){
				jQuery.messager.alert("提示","还款金额不能小于等于0，请重新输入");
				return ;
			}
			jQuery("#lp").form('submit',{
					url:"<%=contextPath %>/springMVC/gd/<%=isAdd ? "addGdYetAdvances"  : "updateGdYetAdvances?id=" + id%>",	
					queryParams:{"gd_id":"<%=gd_id%>","products":products},
					onSubmit:function(){
					var isValid = jQuery(this).form('validate');
					return isValid;
				},
				success:function(rtJson){
					rtJson = eval('(' + rtJson + ')'); 
					if (rtJson.rtState == '0'){
						eval('window.opener.<%=callback%>();');
						window.close();
					}else{
						warningInfo(rtJson.rtMsrg);
					}
				}
			});
		}
		function addRows(ids,lxMoneys,moneys,actual_operation_dates,advances,person_names,yetMoneys,rates,already_moneys,on_moneys){
			
			 if(ids==""){
				  return;
			 }
			 var idArray= new Array();
			 var lxMoneysArray= new Array();
			 var moneysArray= new Array();
			 var on_moneysArray= new Array();
			 var actual_operation_datesArray= new Array();
			 var yetMoneysArray= new Array();
			 var advancesArray= new Array();
			 var person_nameArray= new Array();
			 var already_moneysArray= new Array();
			 var rateArray= new Array();
			 idArray=ids.split(",");
			 lxMoneysArray=lxMoneys.split(",");
			 moneysArray=moneys.split(",");
			 actual_operation_datesArray=actual_operation_dates.split(",");
			 advancesArray=advances.split(",");
			 person_nameArray=person_names.split(",");
			 yetMoneysArray=yetMoneys.split(",");
			 already_moneysArray=already_moneys.split(",");
			 rateArray=rates.split(",");
			 on_moneysArray=on_moneys.split(",");
			 jQuery('#table').datagrid('acceptChanges');
			 lastIndex =-1;
			 var yetMoney=0;
		     var jsondata=jQuery("#table").datagrid("getData");
		     var sum_money= jQuery("#sum_money").numberbox("getValue");
		     for (var i=0;i<idArray.length ;i++ )   
		     {
					for(var j=0;j<jsondata.total;j++){
						if(idArray[i]==jsondata.rows[j].advances_id){
							jQuery.messager.alert("提示","此"+j+"行,借款单已经存在，不能重复添加！");
							typeFlag=1
							return false;
						}
					}
				 yetMoney+=parseFloat(yetMoneysArray[i]);
		    	 addRow(idArray[i],parseFloat(lxMoneysArray[i]).toFixed(2),parseFloat(moneysArray[i]).toFixed(2),actual_operation_datesArray[i],advancesArray[i],person_nameArray[i],parseFloat(yetMoneysArray[i]).toFixed(2),rateArray[i],parseFloat(already_moneysArray[i]).toFixed(2),parseFloat(on_moneysArray[i]).toFixed(2));
			}
		     if(sum_money>0){
		    	 var sumMoney=parseFloat(yetMoney)+parseFloat(sum_money);
		    	 jQuery("#sum_money").numberbox("setValue",sumMoney.toFixed(2));
			 }else{
			 	 jQuery("#sum_money").numberbox("setValue",yetMoney.toFixed(2));
			 }
		}
		function addRow(advances_id,lxMoney,money,actual_operation_date,advances,person_name,yetMoney,rate,already_money,on_money){
			jQuery('#table').datagrid('endEdit', lastIndex);
			jQuery('#table').datagrid('appendRow',{
				advances_id:advances_id,
				fb_advances:advances,
				actual_operation_date:actual_operation_date,
				person_name:person_name,
				money:money,
				on_money:on_money,
				rate:rate,
				lxMoney:lxMoney,
				already_money:already_money,
				yet_money:parseFloat(on_money)+parseFloat(lxMoney)
			});
			var data = jQuery('#table').datagrid('getData');
			jQuery('#table').datagrid('loadData',data);
			lastIndex = jQuery('#table').datagrid('getRows').length-1;
			jQuery('#table').datagrid('selectRow', lastIndex);
			jQuery('#table').datagrid('beginEdit', lastIndex);
		}
		function  jsRate(rowData){
			var date=new Date();
	        var year = date.getFullYear();       //年
	        var month = date.getMonth() + 1;     //月
	        var day = date.getDate();            //日
			var operation_date=year+"-"+month+"-"+day;
			var dates=0;
			if(0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0))){
				dates=366;
			}else{
				dates=365;
			}
			var dateNum=0;
			var lxMoney=0;
			var oneTime=operation_date;
			var twoTime=rowData.actual_operation_date.split(" ");
			dateNum=getDays(oneTime,twoTime[0]);
			lxMoney=parseFloat(rowData.on_money*rowData.rate*dateNum/(100*dates)).toFixed(2);//利息
			return lxMoney;
		}
		function sumMoney(){
			var jsondata=jQuery("#table").datagrid("getData");
			var sumMoney=0;
			for(var i=0;i<jsondata.total;i++){
				sumMoney+=parseFloat(parseFloat(jsondata.rows[i].yet_money));
			}
			jQuery("#sum_money").numberbox("setValue",sumMoney.toFixed(2));
		}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="lp" method="post">
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>
					<td align="right" class="td1" nowrap>工单编号：</td>
					<td class="td2" nowrap>
						<input  id="gd_code" name="gd_code" readOnly value="<%=gd_code%>">
					</td>
					<td align="right" class="td1" nowrap>工单名称：</td>
					<td class="td2" nowrap>
						<input  id="gd_name" name="gd_name" readOnly value="<%=gd_name%>">
					</td>
				</tr>
				<tr>
				
						
					<td align="right" class="td1" nowrap>经办人部门：</td>
					<td class="td2" nowrap  >
						<input  id="dept_name" name="dept_name" readOnly value="<%=dept_name%>"/>
						<input type="hidden" id="dept_id" name="dept_id" readOnly value="<%=dept_id%>"/>
					</td>
					<td align="right" class="td1" nowrap>经办人：</td>
					<td class="td2" nowrap >
						<input type="hidden"  id="person_id" name="person_id"  value="<%=person_id%>"/>
						<input  id="person_name" name="person_name" readOnly value="<%=person%>"/>
					</td>
				
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>申请班组：</td>
						<td class="td2" nowrap >
										<input type="hidden" id="fb_advances_id" name="fb_advances_id"  >
										<input type="text" id="fb_advances" readOnly name="fb_advances"   >
									</td>
					<td align="right" class="td1" nowrap >申请日期：</td>
					<td class="td2" nowrap  >
						<input  id="operation_date" name="operation_date" class="easyui-datetimebox" data-options="required:true">
					</td>
				 <tr>
				 	   <td align="right" class="td1" nowrap>还款金额：</td>
								<td class="td2" nowrap  colspan="3">
									 <input   id="sum_money" name="sum_money" class="easyui-numberbox" readonly="readonly" data-options="required:true,min:0,precision:2"   />(自动计算) 
									<!--<input type="text" id="sum_money" name="sum_money" />-->
								</td>
				 </tr>
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2"  colspan='3'>
						<textarea id="remark" name="remark" style="height:100%;width:99%" rows="6"></textarea>
					</td>
				</tr>
				</tr>
									<tr id="attaTr" style="display:none" >
								      <td nowrap align="right" class="td1">附件明细: </td>
								      <td class="td2"  colspan="3">
								        <input type="hidden" id="attachmentId" name="attachmentId">
								        <input type="hidden" id="attachmentName" name="attachmentName">
								        <span id="showAtt">
								        </span>
								      </td>
							   	    </tr>
								<tr>
							      <td nowrap align="right" class="td1">附件：</td>
							      <td class="td2" colspan="3">
							        	 <div id="fsUploadArea" class="flash" style="width:380px;">
										     <div id="fsUploadProgress"></div>
										     <div>
										       <input type="button" id="btnStart" class="SmallButtonW" value="开始上传" onclick="swfupload.startUpload();" disabled="disabled">&nbsp;&nbsp;
										       <input type="button" id="btnCancel" class="SmallButtonW" value="全部取消" onclick="javascript:swfupload.cancelQueue();jQuery('#fsUploadArea').hide();" disabled="disabled">&nbsp;&nbsp;
										    </div>
									      </div>
									      
										    <div id="attachment1">
									          <span id="spanButtonUpload" title="上传附件"></span>
									        </div>
							      </td>
					   		   </tr>
					  <%if(!"1".equals(isShow)){ %>
							<tr>
								<td align="right" class="td1" nowrap></td>
								<td class="td2" nowrap colspan='3'>
									<div align="left">
										<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="doSubmit(this);">提交</a>
										<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:parent.window.close();">关闭</a>
									</div>
								</td>
							</tr>
					<%} %>
					<tr>
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
	
		
	</body>
</html>